/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import static com.google.android.tv.settings.TvSettings.System.SCREEN_DIM_TIMEOUT;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;
import com.android.settings.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.content.Intent;
import android.content.DialogInterface;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import android.media.AudioManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.SeekBarPreference;
import android.preference.Preference;
import android.provider.Settings;
import android.preference.PreferenceScreen;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceActivity;
import com.google.android.tv.provider.TvUriUtils;
import com.hisense.settings.util.PreferenceUtils;
import com.hisense.settings.device.PairingDevice;
import com.google.android.tv.mediadevices.Device;
import com.google.android.tv.mediadevices.MediaDevicesIntents;
import com.google.android.tv.mediadevices.IMediaDevicesService;
import com.google.android.tv.mediadevices.MediaDevicesConstants;

/*import com.marvell.willowtv.framework.util.atsc.InputSourceType;
 import com.marvell.willowtv.framework.features.LiveTv;
 import com.marvell.willowtv.framework.features.TvFramework;
 import com.marvell.willowtv.framework.features.ParentalControl;
 import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass;
 import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ChannelDetails;
 import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ChannelListElement;
 import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ServiceModificationFlags;
 import com.marvell.willowtv.framework.util.gtv.ChannelStreamInfo;*/
import com.google.android.tv.mediadevices.LoadChannelListTask;
import com.google.android.tv.model.Channel;
import com.hisense.settings.util.Wrapper;
import com.hisense.settings.base.TVBaseDialog;

import java.util.ArrayList;
import java.util.List;
import android.util.Log;
import android.text.TextUtils;

/**
 * Handles settings menu for cc displayoption settings.
 * 
 * @author zhengqingqing
 */
public class PowerOnSettings extends PreferenceActivity implements
		Preference.OnPreferenceChangeListener {

	private static final String TAG = "PowerOnSettings";

	public static final String KEY_POWER_ON_SOURCE = "power_on_source";
	public static final String KEY_POWER_ON_CHANNEL = "power_on_channel";
	public static final String KEY_POWER_ON_SOUND_SWITCH = "power_on_sound_switch";
	public static final String KEY_POWER_ON_SOUND_BAR = "power_on_sound";

	public static final String KEY_POWER_ON_SOURCE_NUM = "power_on_source_num";
	public static final String KEY_POWER_ON_CHANNEL_MAJORNO = "power_on_channel_major";
	public static final String KEY_POWER_ON_CHANNEL_MINOR = "power_on_channel_minor";
	public static final String KEY_POWER_ON_CHANNEL_NAME = "power_on_channel_name";
	public static final String KEY_POWER_ON_CHANNEL_URI = "power_on_channel_uri";
	public static final String KEY_POWER_ON_CHANNEL_URI_ANTENNA = "power_on_channel_uri_antenna";
	public static final String KEY_POWER_ON_CHANNEL_URI_CABLE = "power_on_channel_uri_cable";
	public static final String KEY_POWER_ON_SOUND_ENABLE = "settings_power_sound_enable";
	public static final String VALUE_TV_SOURCE = "1";
	public static final int POWER_SOUND_ENABLE = 1;
	public static final int POWER_SOUND_DISABLE = 0;

	private static final int SOURCE_REMEMBER = 0;
	private static final int SOURCE_TV = 1;
	private static final int SOURCE_COMPOSITE = 2;
	private static final int SOURCE_COMPONENT = 3;
	private static final int SOURCE_HDMI1 = 4;
	private static final int SOURCE_HDMI2 = 5;
	private static final int SOURCE_HDMI3 = 6;
	private static final int SOURCE_HDMI4 = 7;
	private static final int SOURCE_VGA = 8;
	private static String DEVICE_ID = null;
	//private MyLoadChannelListTask mLoadChannelListTask;

	// Remember 0
	// TV 1
	// AV1 2
	// AV2 3
	// Component 4
	// HDMI1 5
	// HDMI2 6
	// HDMI3 7
	// HDMI4 8
	// VGA 9
	private static final int VALUE_DEFAULT_SOURCE = 0;

	private ListPreference mPowerOnSourcePreference;
	private ListPreference mPowerOnChannelPreference;
	private Preference PowerOnSoundPreference;
	private CheckBoxPreference mPowerOnSoundCheckbox;

	// private final LiveTv gLive =
	// TvFramework.getInstance().getLiveTvInstance();
	private Resources mRes = null;

	private String[] channeEntries;
	private String[] channeEntriesValue;
	private String[] channeNumber;
	private String[] channeUri;
	private Boolean channelExisit = false;
	// List<ChannelDetails> channelInfo = null;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "%%%%%%%%%1");
		mRes = getResources();
		Log.d(TAG, "%%%%%%%%%2");
		addPreferencesFromResource(R.xml.power_on_settings);
		Log.d(TAG, "%%%%%%%%%3");
		mPowerOnSourcePreference = (ListPreference) findPreference(KEY_POWER_ON_SOURCE);
		String currentPowerOnSource = mPowerOnSourcePreference.getValue();
		int power_on_source = Settings.Secure.getInt(getContentResolver(),
				"power_on_source_num", 10);

		if (currentPowerOnSource == null || power_on_source == 0) {
			currentPowerOnSource = "0";
		}
		if (power_on_source == 1) {
			currentPowerOnSource = "1";
		}
		mPowerOnSourcePreference.setValue(currentPowerOnSource);
		mPowerOnSourcePreference.setOnPreferenceChangeListener(this);
		updatePowerOnSourceSummary(currentPowerOnSource);
		Log.d(TAG, "%%%%%%%%%");
		mPowerOnChannelPreference = (ListPreference) findPreference(KEY_POWER_ON_CHANNEL);
		if (currentPowerOnSource.equals(VALUE_TV_SOURCE) == true) {
			mPowerOnChannelPreference.setEnabled(true);
			Log.d(TAG, "c$$$$$$$$$$$1");
		} else {
			mPowerOnChannelPreference.setEnabled(false);
			Log.d(TAG, "c$$$$$$$$$$$2");
		}

		Log.d(TAG, "c$$$$$$$$$$$");
		mPowerOnChannelPreference.setOnPreferenceChangeListener(this);

		Log.d(TAG, "############");
		PowerOnSoundPreference = (Preference) findPreference(KEY_POWER_ON_SOUND_BAR);
		mPowerOnSoundCheckbox = (CheckBoxPreference) findPreference(KEY_POWER_ON_SOUND_SWITCH);
		Log.d(TAG, "^^^^");
		setupPowerOnSound();
		Log.d(TAG, "**********");

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		/*mLoadChannelListTask = new MyLoadChannelListTask(PowerOnSettings.this,
				PairingDevice.TUNER_DEVICE_ID);
		mLoadChannelListTask.execute();*/

	}

	public void setDeviceId(String deviceId) {
		DEVICE_ID = deviceId;
	}

	private String setChannelArray(String str) {
		int i = 0;
		String result = null;
		result = str;
		Log.d(TAG, "setChannelArray " + result);
		return result;
	}

	private void setupPowerOnSound() {
		mPowerOnSoundCheckbox.setPersistent(true);
		boolean enabled = mPowerOnSoundCheckbox.isChecked();
		if (enabled) {
			PowerOnSoundPreference.setEnabled(true);
			Settings.Secure.putInt(getContentResolver(),
					KEY_POWER_ON_SOUND_ENABLE, POWER_SOUND_ENABLE);
		} else {
			PowerOnSoundPreference.setEnabled(false);
			Settings.Secure.putInt(getContentResolver(),
					KEY_POWER_ON_SOUND_ENABLE, POWER_SOUND_DISABLE);
		}
		mPowerOnSoundCheckbox
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
					public boolean onPreferenceClick(Preference preference) {
						boolean enabled = mPowerOnSoundCheckbox.isChecked();
						if (enabled) {
							PowerOnSoundPreference.setEnabled(true);
							Settings.Secure.putInt(getContentResolver(),
									KEY_POWER_ON_SOUND_ENABLE,
									POWER_SOUND_ENABLE);
						} else {
							PowerOnSoundPreference.setEnabled(false);
							Settings.Secure.putInt(getContentResolver(),
									KEY_POWER_ON_SOUND_ENABLE,
									POWER_SOUND_DISABLE);
						}
						return true;
					}
				});
	}

	public String getPowerOnSource() {
		mPowerOnSourcePreference = (ListPreference) findPreference(KEY_POWER_ON_SOURCE);
		String value = mPowerOnSourcePreference.getValue();
		return value;
	}

	private void setPowerOnSource(int defaultValue) {
		int value = defaultValue;
	}

	private void updatePowerOnSourceSummary(Object value) {
		CharSequence[] summaries = getResources().getTextArray(
				R.array.power_on_source_entries);
		CharSequence[] values = mPowerOnSourcePreference.getEntryValues();
		for (int i = 0; i < values.length; i++) {
			// Log.i("foo", "Comparing entry "+ values[i] + " to current "
			// + mAnimations.getValue());
			if (values[i].equals(value)) {
				mPowerOnSourcePreference.setSummary(summaries[i]);
				break;
			}
		}
	}

	public void searchChannelNumber(int value) {
		Settings.Secure.putString(getContentResolver(),
				KEY_POWER_ON_CHANNEL_NAME, channeNumber[value]);
		Settings.Secure.putString(getContentResolver(),
				KEY_POWER_ON_CHANNEL_URI, channeUri[value]);

		// save power on channel by tuner mode
		int tunerMode = Wrapper.getWrapperInstance().getTunerMode();
		if (tunerMode == 0) { // antenna
			Settings.Secure.putString(getContentResolver(),
					KEY_POWER_ON_CHANNEL_URI_ANTENNA, channeUri[value]);
		} else { // cable
			Settings.Secure.putString(getContentResolver(),
					KEY_POWER_ON_CHANNEL_URI_CABLE, channeUri[value]);
		}
		Log.d(TAG, channeUri[value] + "KEY_POWER_ON_CHANNEL_NAME "
				+ channeNumber[value]);
	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		Log.d(TAG, "%%%%%%%%%6");
		return false;
	}

	public boolean onPreferenceChange(Preference preference, Object objValue) {
		final String key = preference.getKey();
		if (KEY_POWER_ON_SOURCE.equals(key)) {
			int value = Integer.parseInt((String) objValue);
			try {
				mPowerOnSourcePreference.setValue((String.valueOf(value)));
				Settings.Secure.putInt(getContentResolver(),
						KEY_POWER_ON_SOURCE_NUM, value);
				updatePowerOnSourceSummary(objValue);
				if (value != SOURCE_REMEMBER) {
					String sourceId = getSourceUrlString(value);
					Settings.Secure.putString(getContentResolver(),
							"power_on_device", sourceId);
					Uri dataUri = TvUriUtils.PASSTHROUGH_URI
							.buildUpon()
							.appendQueryParameter(
									TvUriUtils.DEVICE_ID_QUERY_PARAMETER,
									sourceId).build();
					Intent srcintent = new Intent(Intent.ACTION_VIEW, dataUri);
					Log.d(TAG, "power on setting source bootIntent: "
							+ srcintent);
					PreferenceUtils.setBootIntent(getContentResolver(),
							srcintent);

				}
				if (Integer.toString(value).equals(VALUE_TV_SOURCE)
						&& channelExisit) {
					mPowerOnChannelPreference.setEnabled(true);
				} else {
					mPowerOnChannelPreference.setEnabled(false);
				}

			} catch (NumberFormatException e) {
				Log.e(TAG, "could not persist screen timeout setting", e);
			}
		} else if (KEY_POWER_ON_CHANNEL.equals(key)) {
			Log.d(TAG, "%%%%%%%%%4");
			if (mPowerOnChannelPreference.isEnabled() == true) {
				Log.d(TAG, "%%%%%%%%%5");
				int value = Integer.parseInt((String) objValue);
				try {
					searchChannelNumber(value);

				} catch (NumberFormatException e) {
					Log.e(TAG, "could not persist screen timeout setting", e);
				}
			}
		}

		return true;
	}

	private void populatePowerOnChannelLists(ListPreference powerOnChannelList) {
		buildSupportedPwerOnChannelListPreference(powerOnChannelList);

		powerOnChannelList
				.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						return handleSelectItem(newValue);
					}
				});
	}

	private void buildSupportedPwerOnChannelListPreference(
			ListPreference powerOnChannelList) {
		String[] supportedEntries = new String[5];// = new
													// String[supportedModes.length];
		String[] supportedValues = new String[5];// = new
													// String[supportedModes.length];
		// TODO huangjiufa
		for (int i = 0; i < 5/* supportedModes.length */; i++) {
			supportedEntries[i] = "entry: " + Integer.toString(i);
			supportedValues[i] = "entryvalue: " + Integer.toString(i);
		}
		powerOnChannelList.setEntries(supportedEntries);
		powerOnChannelList.setEntryValues(supportedValues);
	}

	private boolean handleSelectItem(Object newValue) {

		return false;
	}

	private String GetChannelUriFromChannelDBByChannelNumber(Context context,
			String channel_number) {
		ContentResolver resolver = context.getContentResolver();
		ContentValues values = new ContentValues();
		Uri uri = Uri
				.parse("content://com.google.android.tv.provider/channel_listing");
		Cursor mcursor = resolver.query(uri, new String[] { "channel_number",
				"channel_uri" }, null, null, null);
		String channelurl = null;
		try {
			while (mcursor.moveToNext()) {
				// String channel_name =
				// Settings.Secure.getString(getContentResolver(),"power_on_channel_name");
				String channelName = mcursor.getString(mcursor
						.getColumnIndexOrThrow("channel_number"));
				if (channelName == null)
					continue;
				if (channelName.equals(channel_number)) {
					// return
					// mcursor.getString(mcursor.getColumnIndexOrThrow("channel_uri"));
					channelurl = mcursor.getString(mcursor
							.getColumnIndexOrThrow("channel_uri"));
					break;
				}
			}

		} finally {
			if (mcursor != null) {
				try {
					mcursor.close();
				} catch (Exception e) {
				}
			}
		}
		return channelurl;
	}

	private String getSourceUrlString(int source_num) {
		String str = null;

		if (source_num == SOURCE_TV) {
			str = PairingDevice.TUNER_DEVICE_ID;
		} else if (source_num == SOURCE_COMPOSITE) {
			str = PairingDevice.COMPOSITE_DEVICE_ID;
		} else if (source_num == SOURCE_COMPONENT) {
			str = PairingDevice.COMPONENT_DEVICE_ID;
		} else if (source_num == SOURCE_HDMI1) {
			str = PairingDevice.HDMI1_DEVICE_ID;
		} else if (source_num == SOURCE_HDMI2) {
			str = PairingDevice.HDMI2_DEVICE_ID;
		} else if (source_num == SOURCE_HDMI3) {
			str = PairingDevice.HDMI3_DEVICE_ID;
		} else if (source_num == SOURCE_HDMI4) {
			str = PairingDevice.HDMI4_DEVICE_ID;
		} else if (source_num == SOURCE_VGA) {
			str = PairingDevice.VGA_DEVICE_ID;
		}
		return str;

	}

	/*private List<Channel> channels = new ArrayList<Channel>();

	public class MyLoadChannelListTask extends LoadChannelListTask {
		private final Context context;

		public MyLoadChannelListTask(Context context, String deviceId) {

			super(context, deviceId,
					LoadChannelListTask.FLAG_ENABLED_CHANNELS_ONLY);

			this.context = context;
			Log.d(TAG, "deviceId " + deviceId);

		}

		@Override
		protected void onPostExecute(List<Channel> result) {
			super.onPostExecute(result);
			channels = result;
			Log.d(TAG, "channel " + channels);
			Log.d(TAG, "result " + result);
			int size = channels.size();

			if (size <= 0) {
				mPowerOnChannelPreference
						.setEntries(R.array.power_on_channel_entries);
				mPowerOnChannelPreference
						.setEntryValues(R.array.power_on_channel_values);
				mPowerOnChannelPreference.setEnabled(false);
				return;
			} else {
				channeEntries = new String[size];
				channeEntriesValue = new String[size];
				channeNumber = new String[size];
				channeUri = new String[size];
			}

			Log.d(TAG, "channel list size=" + channels.size());
			int i = 0;
			int focusIndex = 0;
			String channelUriString = Settings.Secure.getString(
					getContentResolver(), KEY_POWER_ON_CHANNEL_URI);
			//ChannelDetails chDetail = null;
			Log.d(TAG, "channelUriString=" + channelUriString);
			if (!TextUtils.isEmpty(channelUriString)) {
				Uri channelUri = Uri.parse(channelUriString);
				ChannelStreamInfo csi = new ChannelStreamInfo(
						PairingDevice.TUNER_DEVICE_ID, channelUri);
				chDetail = new ChannelDetails(
						csi.getChannelNumber().getMajor(), csi
								.getChannelNumber().getMinor(),
						csi.getChannelName(), csi.getServiceId(), 0);
			}
			for (Channel ch : channels) {
				String channelNum = ch.getChannelNumberAsString();
				if (channelNum != null) {
					Log.d(TAG,
							"channel number=" + ch.getChannelNumberAsString());
					channeEntriesValue[i] = Integer.toString(i);
					channeNumber[i] = channelNum;
					channeEntries[i] = setChannelArray(channelNum);
					channeUri[i] = ch.getUri();

					if (chDetail != null
							&& Wrapper.getWrapperInstance().isSameChannel(
									chDetail, ch))
						focusIndex = i;
					i++;
				}
			}
			mPowerOnChannelPreference.setEntries(channeEntries);
			mPowerOnChannelPreference.setEntryValues(channeEntriesValue);
			Log.d(TAG, "focusIndex=" + focusIndex);
			mPowerOnChannelPreference.setValueIndex(focusIndex);
			channelExisit = true;
			if (mPowerOnChannelPreference.getValue() == null) {
				mPowerOnChannelPreference.setValue("0");
				searchChannelNumber(0);
			}

		}

		@Override
		protected void onPreExecute() {

			channels.clear();

			super.onPreExecute();

		}

	}*/

}
